const path = require('path')
const fse = require('fs-extra')
const inquirer = require('inquirer')
const validateProjectName = require('../utils/validate-package-name')
const { exit, chalk } = require('@vue/cli-shared-utils')
const Creator = require('./Creator')
const { getPromptModules } = require('../utils/createTools')
// const { promisify } = require("util");

// 创建项目
const create = async (projectName, options) => {
  if (options.proxy) {
    process.env.HTTP_PROXY = options.proxy
  }

  // 判断是否写了projectName
  // 校验name是否符合期望
  if (!projectName) {
    const { inputValue } = await inquirer.prompt({
      type: 'input',
      name: 'inputValue',
      message: 'project-name?'
    })
    projectName = inputValue
  }

  const inCurrent = projectName === '.'
  const name = inCurrent ? path.relative('../', cwd) : projectName

  const result = validateProjectName(name)
  if (!result.validForNewPackages) {
    console.error(chalk.red(`Invalid project name: "${name}"`))
    result.errors &&
      result.errors.forEach((err) => {
        console.error(chalk.red.dim('Error: ' + err))
      })
    result.warnings &&
      result.warnings.forEach((warn) => {
        console.error(chalk.red.dim('Warning: ' + warn))
      })
    exit(1)
  }

  // 判断当前文件夹是否存在同名目录
  const cwd = options.cwd || process.cwd() // 获取当前命令执行时的工作目录
  const targetDir = path.resolve(cwd, projectName || '.') // 目标目录

  if (fse.existsSync(targetDir) && !options.merge) {
    if (options.force) {
      await fse.remove(targetDir);
    } else {
      if (inCurrent) {
        const { ok } = await inquirer.prompt([
          {
            name: "ok",
            type: "confirm",
            message: `Generate project in current directory?`,
          },
        ]);
        if (!ok) {
          return;
        }
      } else {
        const { action } = await inquirer.prompt([
          {
            name: "action",
            type: "list",
            message: `Target directory ${chalk.cyan(
              targetDir
            )} already exists. Pick an action:`,
            choices: [
              { name: "Overwrite", value: "overwrite" },
              { name: "Merge", value: "merge" },
              { name: "Cancel", value: false },
            ],
          },
        ]);
        if (!action) {
          return;
        } else if (action === "overwrite") {
          console.log(`\nRemoving ${chalk.cyan(targetDir)}...`);
          await fse.remove(targetDir);
        }
      }
    }
  }

  const creator = new Creator(name, targetDir, getPromptModules())
  await creator.create(options)
}

module.exports = {
  create
}
